import glob
from PIL import Image
from easygui import diropenbox
from os import *
from os.path import splitext,basename,getsize

#压缩函数
def zip(dir):
    img = Image.open(dir)
    f_size = getsize(dir)/(1024.0*1024)
    if f_size > 0.7:
        rate = 2
        
    else:
        rate = 1
    size = (int(img.height/rate),int(img.width/rate))
    img.thumbnail(size)
    return img

#保存函数
def save(dir,img):
    ext = splitext(dir)[1]
    img.save('image_thumbnail\\'+basename(dir),img.format)

if __name__ == "__main__":
    dir = diropenbox("open a path...")
    if dir == None:
        _exit(0)
    chdir(dir)
    try:
        mkdir("image_thumbnail")
    except:
        pass
    pic = glob.glob(r"*.png")+glob.glob(r"*.jpg")+glob.glob(r"*.jpeg")#这里应该可以用正则表达式的但我又不会orz

    for img_dir in pic:
        tbnl_img = zip(img_dir)
        save(img_dir,tbnl_img)
        print("已完成【"+basename(img_dir)+"】的压缩！")
    print("一共完成"+str(len(pic))+"张图片的压缩！")
